<?php

namespace addons\fzdc\controller;

use addons\epay\library\Service;
use app\admin\model\fzdc\Address;
use app\admin\model\fzdc\coupon\Receive;
use app\admin\model\fzdc\goods\Goods;
use app\admin\model\fzdc\goods\SkuItem;
use app\admin\model\fzdc\goods\SkuProduct;
use app\admin\model\fzdc\message\Push;
use app\admin\model\fzdc\order\Cart;
use app\admin\model\fzdc\order\Detail;
use app\admin\model\fzdc\order\Recharge;
use app\admin\model\fzdc\prin\Prin;
use app\admin\model\fzdc\store\Label;
use app\admin\model\fzdc\store\Refund;
use app\admin\model\fzdc\store\Revenue;
use app\admin\model\fzdc\store\Sear;
use app\admin\model\fzdc\store\Seart;
use app\admin\model\fzdc\store\Store;
use app\admin\model\fzdc\Userdetail;
use app\common\controller\Api;
use app\admin\model\fzdc\coupon\Coupon;
use app\common\model\MoneyLog;
use app\admin\model\fzdc\Address as Ad;
use think\Cache;
use think\Db;
use app\admin\model\fzdc\order\Order as Od;
use app\admin\model\fzdc\distribution\Log as DL;

use think\Exception;
use think\Log;
use think\Model;
use think\Queue;
use think\Request;
use think\Hook;

use addons\fzdc\library\XinYe\PrintService as PService;
use addons\fzdc\library\XinYe\util\NoteFormatter;
use app\admin\controller\fzdc\user\User;
use app\admin\model\User as ModelUser;
use Yansongda\Pay\Pay;

class Order extends Api
{
    protected $noNeedLogin = ['empty', 'notifyx', 'recharge', 'refund_notifyx', 'seat_list', 'seat', 'cancel_reservation'];
    protected $noNeedRight = ['*'];
    protected $config = [];
    protected $modelstore = null;
    protected $modelcoupon = null;
    protected $modeladdress = null;

    public function __construct(Request $request = null)
    {
        $this->config = get_addon_config("fzdc");
        $this->modelstore = new \app\admin\model\fzdc\store\Store;
        $this->modelcoupon = new \app\admin\model\fzdc\coupon\Coupon;
        $this->modeladdress = new \app\admin\model\fzdc\user\Address;
        parent::__construct($request);
    }

    /*
     * 消费记录
     */
    public function recharges()
    {
        $page   = $this->request->post('page')??1;  //页码
        $limit  = $this->request->post('limit')??10; //每页显示条数
        $user_id = $this->auth->id;

        $recharge_list = \app\admin\model\fzdc\order\Order::where(['user_id' => $user_id])->where('status', 'in', '2,3,6,7,8,10')->order('createtime desc')->field('type,pay_type,order_amount_total,createtime')->paginate(["page"=>$page,"list_rows"=>$limit]);

        $this->success('成功', $recharge_list);}

    /*
     * 门店扫用户码支付
     */
    public function pay_code(){
        $order_no = $this->request->post('order_no');
        $user_id = $this->request->post('user_id');
        if (!$order_no){
            $this->error("缺少订单号");
        }
        if (!$user_id) {
            $this->error("缺少用户id");
        }
        //判断订单状态
        $order_res = Od::where(["order_no" => $order_no])->find();
        if (!$order_res) {
            $this->error("订单不存在");
        }
        if ($order_res['status']!= 1) {
            $this->error("订单状态异常");
        }
        if ($order_res['dc_type'] == 1){
            $this->error("该订单为用户点餐");
        }
        //判断用户是否存在
        $user_res = \app\admin\model\fzdc\user\User::where(["id" => $user_id])->find();
        if (!$user_res) {
            $this->error("用户不存在");
        }
        //判断用户余额是否足够
        $user_money = $user_res['money'];
        if ($user_money < $order_res['order_amount_total']) {
            $this->error("余额不足");
        }
        //扣除用户余额
        $user_res->money = $user_money - $order_res['order_amount_total'];
        $user_res->save();
        Od::where(["order_no" => $order_no])->update(["status" => 3,"pay_type"=>3, "pay_time" => time(),'dc_type'=>1,"user_id"=> $user_id,"updatetime"=>time()]);
        Sear::where("FIND_IN_SET('{$order_res['seat_id']}', id)")->update(['use_status' => 1]);
        //分销
        Log::info("钱包支付分销");
        $no = $order_res->order_no;
        Hook::listen('fzdc_distribution', $no);

        //异步推送消息
        //判断用户是否订阅消息推送
        $userInfo = Userdetail::get(["user_id" => $user_id]);
        Log::info("推送消息开始");
        if ($userInfo['subscribe'] == 1) {
            Log::info("进入推送1");
            $message = Push::where(["type" => 1])->find();
            if ($message) {
                Log::info("进入推送2");
                if (!empty($message['multiplejson'])) {
                    $json = json_decode($message['multiplejson'], true);
                    //参数名对应订阅消息详细内容参数 （以下为测试）
                    $data = [];
                    foreach ($json as $jv) {
                        switch ($jv['title']) {
                            case '1':
                                $data['data'][$jv['keyword']]['value'] = $this->config['share_title'];
                                break;
                            case '2':
                                $data['data'][$jv['keyword']]['value'] = $order_res->order_no;
                                break;
                            case '3':
                                $data['data'][$jv['keyword']]['value'] = $order_res->order_amount_total;
                                break;
                            case '4':
                                $data['data'][$jv['keyword']]['value'] = date("Y-m-d H:i:s", time());
                                break;

                        }
                    }
                    //Log::info("推送数据：" . json_encode($data['data']));
                    $data['order_id'] = $order_res['id'];
                    $data['openid'] = $userInfo['openid'];
                    $data['masterplate'] = $message->masterplate;
                    Queue::later(2, 'addons\fzdc\job\SendMessage', $data, 'dcOrderQueue');
                }

            }

        }

        Log::info("进入推送===》",json_encode($order_res));
        Log::info("进入推送222===》",json_encode($user_money));
        $m_memo = "订餐减少余额";
        MoneyLog::create(['user_id' => $user_id, 'money' => $order_res['order_amount_total'], 'before' => $user_money, 'after' => $user_money - $order_res['order_amount_total'], 'memo' => $m_memo]);

        $store = Store::get($order_res['store_id']);
        $store->setInc("balance", $order_res['order_amount_total']);
        $store->save();
        //增加商家收入明细
        Revenue::create(["store_id" => $order_res['store_id'], "type" => 1,"pay_type"=>3, "amount" => $order_res['order_amount_total'], "user_id" => $user_id, "createtime" => time(), "updatetime" => time()]);
//        $this->print($order_res);
        $this->success('支付成功');
    }

    /*
     * 充值优惠列表
     */
    public function recharge()
    {
        $data = Recharge::where(["status" => "normal"])->select();
        $this->success("success", $data);
    }

    /*
     * 桌号信息
     */
    public function seat()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error("缺少桌号id");
        }
        $data = Sear::get($id);
        $store = Store::get($data['store_id']);
        if (!$data) {
            $this->error("数据异常");
        }
        $data['img'] = empty($data['img']) ? $data['img'] : cdnurl($data['img'], true);
        $data['image'] = empty($data['image']) ? $data['image'] : cdnurl($data['image'], true);

        // 获取当前日期
        $currentDate = date('Y-m-d');
        $day = [];
        // 循环输出最近一个星期的日期
        $yy_time = get_addon_config('fzdc')['yy_time'];
        for ($i = 0; $i < $yy_time; $i++) {
            // 使用strtotime函数将当前日期加上$i天
            $date = date('Y-m-d', strtotime($currentDate . ' +' . $i . ' days'));
            // 格式化日期
            if ($i == 0) {
                $formattedDate = '今天';
            } elseif ($i == 1) {
                $formattedDate = '明天';
            } else {
                $formattedDate = date('m月d日', strtotime($date));
            }
            $day[$i]['day'] = $formattedDate;
            $day[$i]['day_date'] = strtotime($date);

            //获取时间区间
            $rule = \app\admin\model\fzdc\store\Rule::order("ks_times asc")->select();

            if (!$rule) {
                $this->error("请先在后台添加规则");
            }
            $time = [];
            foreach ($rule as $rk => $rv) {
                $start_time = strtotime($rv['ks_times']);
                $end_time = strtotime($rv['js_times']);
                $current_time = $start_time;
                $j = 0;
                while ($current_time <= $end_time) {
                    $formatted_time = date('H:i', $current_time);
                    $time[$rk][$j]['status'] = 1;
                    $time[$rk][$j]['tag'] = Label::get($rv['label_id'])['title'];

                    $time[$rk][$j]['time'] = $formatted_time;
                    $time_data = strtotime(date('Y-m-d ' . $formatted_time, strtotime($currentDate . ' +' . $i . ' days')));
                    $time[$rk][$j]['time_date'] = $time_data;
                    $time[$rk][$j]['status'] = 0;
                    if (strtotime(date('Y-m-d H:i', $current_time)) + ($i * 86400) < time()) {
                        $time[$rk][$j]['status'] = 2;
                    }
                    //查询预约记录表
                    $order_res = Od::where(["subscribe_time" => $time_data])->where("FIND_IN_SET('{$id}', seat_id)")->whereNotIn('status', [4, 5, 9])->find();
                    if ($order_res) {
                        $time[$rk][$j]['status'] = 1;
                    }

                    $current_time += $rv['interval'] * 60 * 60;
                    $j++;
                }
            }
            $result = call_user_func_array('array_merge', $time);
            foreach ($result as $rrk => $rrv) {
                if ($rrv['status'] == 2) {
                    unset($result[$rrk]);
                }
            }
            $day[$i]['time'] = array_merge($result);

        }
        $data['day'] = $day;
        $data['deposit'] = $store['deposit'];
        //判断桌号有没有未支付的订单
        $order_res = Od::where(["status" => 1,"order_type"=>3])->where("FIND_IN_SET('{$id}', seat_id)")->order("id", "desc")->find();
        if (!$order_res){
            $order_res = Od::where(["p_type" => 2,"status"=>['in',[6,7]]])->where("FIND_IN_SET('{$id}', seat_id)")->order("id", "desc")->find();
        }
        if ($order_res) {
            $data['order_id'] = $order_res['id'];
        }else{
            $data['order_id'] = 0;
        }
        $this->success("success", $data);
    }

    /*
     * 获取桌号列表
     */
    public function seat_list()
    {
        $store_id = $this->request->post("store_id");    //门店id
        $user_status = $this->request->post("user_status");    //状态
        $where = [];
        if ($user_status){
            $where['use_status'] = ['=',$user_status];
        }
        //参数校验
        if (!$store_id) {
            $this->error("门店id不能为空");
        }
        $list = Seart::select();
        $arr = [];
        if ($list) {
            foreach ($list as $lk => $lv) {
                $arr[$lk]['type'] = $lv['title'];
                $arr[$lk]['data'] = Sear::where(["store_id" => $store_id, "type" => $lv['id']])->where($where)->field('id,title,no,img,use_status')->select()->each(function ($item) {
                    if ($item->img) {
                        $item->img = cdnurl($item->img, true);
                    }
                    if ($item->use_status == 2){
                        $order = Od::where(['status' => 1,"order_type"=>3])->where("FIND_IN_SET('{$item->id}', seat_id)")->find();
                        if ($order) {
                            $item->order_time = $order['createtime'];
                            $item->order_id = $order['id'];
                        }else{
                            $item->order_time = time();
                            $item->order_id = 0;
                        }
                    }
                    $item->is_show = false;
                });
            }

        }
        $this->success("success", $arr);
    }

    /*
     * 预约桌号
     */
    public function reservation()
    {
        $userId = $this->auth->id;
        $id = $this->request->post("id"); //桌号
        $subscribe_time = $this->request->post("subscribe_time"); //预约时间
        $dd_time = $this->request->post("dd_time"); //到店时间
        $subscribe_name = $this->request->post("subscribe_name"); //订座人
        $subscribe_tel = $this->request->post("subscribe_tel"); //手机号
        if (!$id) {
            $this->error("桌号不能为空");
        }
        if (!$subscribe_time) {
            $this->error("预约时间不能为空");
        }
        if (!$subscribe_name) {
            $this->error("订座人不能为空");
        }
        if (!$subscribe_tel) {
            $this->error("手机号不能为空");
        }
        if ($subscribe_time < time()) {
            $this->error("预约时间不能小于当前时间");
        }
        //查询预约记录表
        $order_res = Od::where(["subscribe_time" => $subscribe_time])->where("FIND_IN_SET('{$id}', seat_id)")->whereNotIn('status', [4, 5, 9])->find();
        if ($order_res) {
            $this->error("当前时间已被预订");
        }
        $data = Sear::get($id);
        $store = Store::get($data['store_id']);
        if ($store['deposit'] == 0) {
            $status = 10;
        } else {
            $status = 1;
        }
        $orderNo = fzdc_orderNo($userId);
        $data = [
            "order_no" => $orderNo,            //订单编号
            "order_type" => 4,                   //订单类型
            "type" => 1,                   //订单类型
            "user_id" => $userId,             //用户id
            "store_id" => $store['id'],        //门店id
            "status" => $status,             //订单状态
            "order_amount_total" => $store['deposit'],   //实际付款金额
            "subscribe_time" => $subscribe_time,     //预约时间
            "subscribe_tel" => $subscribe_tel,      //预留电话
            "seat_id" => $id,                 //桌号id
            "subscribe_name" => $subscribe_name,     //预约人姓名
            "dd_time" => $dd_time,            //到店时间
        ];

        //数据入库
        Db::startTrans();
        try {
            //插入订单表
            Od::create($data);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error("数据录入失败：" . $e->getMessage());
        }
        if ($status == 10) {
            //订单放入队列 超过预约时间两小时自动变成已完成
            $data = ["orderNo" => $orderNo, "type" => 2];
            $later_time = ($subscribe_time + 7200) - time();
            Queue::later($later_time, 'addons\fzdc\job\Overtime', $data, 'dcOrderQueue');
            //到预约时间桌号自动变成使用中
            Queue::later($subscribe_time-time(), 'addons\fzdc\job\Overtime', ["orderNo" => $orderNo, "type" => 4], 'dcOrderQueue');
        }


        $this->success("成功", ["orderNo" => $orderNo]);


    }

    /*
     * 取消预约
     */
    public function cancel_reservation()
    {
        $userId = $this->auth->id;
        $order_no = $this->request->post("order_no");    //订单号
        if (!$order_no) {
            $this->error("缺少订单号");
        }
        $orderd = Od::get(['order_no' => $order_no]);
        if (!$orderd) {
            $this->error("订单不存在");
        }


        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $userId, "status" => "normal"])->find();
        if (!$res) {
            if ($userId != $orderd['user_id']) {
                $this->error("用户不正确");
            }
            if (time() > $orderd['subscribe_time']) {
                $this->error("已超过预约时间,不可取消预约");
            }
        }


        if ($orderd['order_amount_total'] == 0) {
            $orderd->status = 5;
            $orderd->save();
        } else {
            $refund_insert_data['order_id'] = $orderd['id'];
            $refund_insert_data['store_id'] = $orderd['store_id'];
            $refund_insert_data['amount'] = $orderd['order_amount_total'];
            $refund_insert_data['user_id'] = $orderd['user_id'];
            //判断是否钱包支付
            if ($orderd['pay_type'] == 2) {
                //退款到钱包
                //增加收入支出明细
                Revenue::create(["store_id" => $orderd['store_id'], "type" => 2, "amount" => $orderd['order_amount_total'], "user_id" => $orderd['user_id'], "createtime" => time(), "updatetime" => time()]);
                //增加退款流水
                $refund_insert_data['refund_status'] = 2;
                Refund::create($refund_insert_data);
                $store = Store::get($orderd['store_id']);
                $store->setDec("balance", $orderd['order_amount_total']);
                $store->save();
                $user = \app\admin\model\User::get($orderd['user_id']);
                $user->setInc("money", $orderd['order_amount_total']);
                $user->save();
                $orderd->status = 5;
                $orderd->save();
                $this->success("退款成功");
            }
            //查询退款开关
            if ($this->config['refund_switch']) {
                //原路返回
                Db::startTrans();
                try {
                    $order['transaction_id'] = $orderd['out_trade_no'];
                    $order['out_refund_no'] = date('YmdHis') . substr(bcadd($order_no, strrev(date('YmdHis')), 0), -8) . bcadd($order_no, time(), 0);
                    $order['total_fee'] = bcmul($orderd['order_amount_total'], 100, 0); // 原支付交易的订单总金额
                    $order['refund_fee'] = bcmul($orderd['order_amount_total'], 100, 0); // 退款金额
                    $order['notify_url'] = "";
                    $config = Service::getConfig();
                    $pay = Pay::wechat($config);
                    $result = $pay->refund($order);
                    Log::info("退款结果：" . json_encode($result));
                    if ($result['return_code'] == "SUCCESS") {
                        Log::info("退款成功，退款单号：" . $orderd['out_refund_no']);
                        $orderd->status = 5;
                        $orderd->out_refund_no = $orderd['out_refund_no'];
                        $orderd->refund_id = $result['refund_id'];
                        $orderd->save();
                        //增加收入支出明细
                        Revenue::create(["store_id" => $orderd['store_id'], "type" => 2, "amount" => $orderd['order_amount_total'], "user_id" => $orderd['user_id'], "createtime" => time(), "updatetime" => time()]);
                        //增加退款流水
                        $refund_insert_data['refund_status'] = 2;
                        Refund::create($refund_insert_data);
                    } else {
                        $orderd->last_status = $orderd->status;
                        $orderd->status = 4;
                        $orderd->out_refund_no = $orderd['out_refund_no'];
                        $orderd->refund_id = $result['refund_id'];
                        $orderd->save();
                        //手动退款
                        $refund_insert_data['refund_status'] = 1;
                        Refund::create($refund_insert_data);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error("退款失败：" . $e->getMessage() . ",行号：" . $e->getLine() . ",文件：" . $e->getFile());
                }
            } else {
                //手动退款
                $refund_insert_data['refund_status'] = 1;
                $orderd->last_status = $orderd->status;
                $orderd->status = 4;
                $orderd->save();
                Refund::create($refund_insert_data);
            }
        }
        $this->success("取消成功");
    }

    /*
     * 预约订单已完成
     */
    public function over_reservation()
    {
        $order_no = $this->request->post("order_no");    //订单号
        if (!$order_no) {
            $this->error("缺少订单号");
        }
        $order = Od::get(['order_no' => $order_no]);
        if (!$order) {
            $this->error("订单不存在");
        }
        if (time() < $order['subscribe_time']) {
            $this->error("还未过预约时间,不可完成");
        }
        $order->status = 3;
        $order->save();
        $this->success("success");
    }

    /*
     * 加入购物车
     */
    public function joinCar()
    {
        Log::info("加入购物车");
        $user_id = $this->auth->id;
        $store_id = $this->request->post("store_id");       //门店id
        $goods_id = $this->request->post("goods_id");       //商品id
        $item_id = $this->request->post("spu_id")??"";          //商品规格id
        $spu_info = $this->request->post("spu_info/a")??[];     //spu_info 单规格传
        $count = $this->request->post("count");             //商品数量
        $order_type = $this->request->post("order_type")?$this->request->post("order_type"):0;   //order_type
        //参数校验
        if (!$store_id) {
            $this->error("门店不能为空");
        }
        if (!$goods_id) {
            $this->error("商品不能为空");
        }

        //判断是否支持取货方式
        $store = Store::get($store_id);
        if ($order_type == 1) {
            if (!$store['delivery_switch']) {
                $this->error("该门店不支持自提");
            }
        } elseif($order_type == 2) {
            if (!$store['takeaway_switch']) {
                $this->error("该门店不支持外卖");
            }
        }


        $is_business = 0;
        $startTime = $store['start_times'];
        $endTime = $store['end_times'];
        $currentTime = date("H:i:s");
        if ($endTime < $startTime) {
            if ($currentTime >= $startTime || $currentTime < $endTime) {
                $is_business = 1;
            }
        } else {
            if ($currentTime >= $startTime && $currentTime < $endTime) {
                $is_business = 1;
            }
        }

        if (!$store['trade_switch']) {
            $is_business = 0;
        }
        if (!$is_business) {
            $this->error("该门店歇业中");
        }

        $goods = Goods::get($goods_id);
        if (!$goods) {
            $this->error("商品不存在");
        }
        if ($goods['type']==1){
            //将spu_info转成hash值
            $hash_key = md5(json_encode($spu_info));
            $cart_info = Cart::where(["goods_id" => $goods_id, "user_id" => $user_id , "spu_hash" => $hash_key])->find();
//            var_dump($cart_info);die;
            if (!$cart_info){
                //加入购物车
                $item_name = "";
                $price = $goods['price'];
                if (!empty($spu_info)){
                    foreach ($spu_info as $v) {
                        if ($v['count']<=0){
                            continue;
                        }
                        $sku_item = SkuItem::get($v['spu_id']);
                        if (!$sku_item){
                            $item_name = $goods['title'].'/';
                        }else{
                            $sku_product = SkuProduct::where(["goods_id" => $goods_id, "key" => $v['spu_id']])->find();

                            $item_name .= $sku_item['name'] . '*'.$v['count'].'/';
                            $price = bcadd($price,bcmul($sku_product['price'], $v['count'], 2),2);
                        }

                    }
                    $item_name = substr($item_name, 0, -1);
                }

                Cart::create([
                    "user_id" => $user_id,
                    "store_id" => $store_id,
                    "goods_id" => $goods_id,
                    "item_name" => $item_name,
                    "price" => $price,
                    "count" => 1,
                    "order_type" => $order_type,
                    "type" => 1,
                    "spu_info" => json_encode($spu_info),
                    "spu_info_ys" => json_encode($spu_info),
                    "spu_hash" => $hash_key,
                    "createtime" => time(),
                    "updatetime" => time(),
                ]);
            }else{
                $new_ku_sku_info = $new_spu_info = [];

                if (!empty(json_decode($cart_info['spu_info'], true))){
                    $ku_sku_info = json_decode($cart_info['spu_info'], true);
                    //ku_sku_info和spu_info合并 相同的spu_id数量相加
                    foreach ($ku_sku_info as $v) {
                        $new_ku_sku_info[$v['spu_id']] = $v['count'];
                    }
                    foreach ($spu_info as $v) {
                        if (isset($new_ku_sku_info[$v['spu_id']])) {
                            $new_ku_sku_info[$v['spu_id']] += $v['count'];
                        } else {
                            $new_ku_sku_info[$v['spu_id']] = $v['count'];
                        }
                    }
                    //将new_ku_sku_info键和值转成二维数组
                    $new_spu_info = [];
                    foreach ($new_ku_sku_info as $k => $v) {
                        $new_spu_info[] = ["spu_id" => $k, "count" => $v];
                    }

                    $item_name = $cart_info['item_name'];
                }else{
                    $item_name = "";
                }



                Cart::where([
                    "user_id" => $user_id,
                    "store_id" => $store_id,
                    "goods_id" => $goods_id,
                    "spu_hash" => $cart_info['spu_hash'],
                ])->update([
                    "item_name" => $item_name,
                    "count" => $cart_info['count']+1,
                    "spu_info" => json_encode($new_spu_info),
                    "updatetime" => time(),
                ]);
            }

        }else{

            //多规格
            if (!$item_id) {
                $this->error("规格不能为空");
            }
            if (!$count) {
                $this->error("数量不能为空");
            }
            //判断库存
            $stock = SkuProduct::where(["goods_id" => $goods_id, "key" => $item_id])->value("stock");
            if ($count > $stock) {
                $this->error("库存不足");
            }
            //先判断购物车是否有此订单
            $res = Cart::where(["store_id" => $store_id, "goods_id" => $goods_id, "item_id" => $item_id, "user_id" => $user_id])->find();
            if ($res) {
                //增加此订单的购买数量
                Cart::where("id", $res['id'])->setInc("count", $count);
            } else {
                //添加购物车
                $key = explode("_", $item_id);
                $item_name = "";
                foreach ($key as $v) {
                    $item_name .= SkuItem::where(["id" => $v])->value("name") . '/';
                }
                $item_name = substr($item_name, 0, -1);
                $price = SkuProduct::where(["goods_id" => $goods_id, "key" => $item_id])->value("price");
                Cart::create([
                    "user_id" => $user_id,
                    "store_id" => $store_id,
                    "goods_id" => $goods_id,
                    "item_id" => $item_id,
                    "item_name" => $item_name,
                    "price" => $price,
                    "count" => $count,
                    "order_type" => $order_type,
                    "createtime" => time(),
                    "updatetime" => time(),
                ]);
            }
        }

        $this->success("添加购物车成功");

    }

    /*
     * 修改购物车规格
     */
    public function changeSpec()
    {
        $user_id = $this->auth->id;
        $cart_id = $this->request->post("cart_id");
        $item_id = $this->request->post("spu_id")??"";          //商品规格id
        $spu_info = $this->request->post("spu_info/a")??[];     //spu_info 单规格传
        if (!$cart_id) {
            $this->error("缺少购物车id");
        }
        $cart_info = Cart::get($cart_id);
        if (!$cart_info) {
            $this->error("购物车不存在");
        }
        $goods_id = $cart_info['goods_id'];
        $goods = Goods::get($goods_id);
        if (!$goods) {
            $this->error("商品不存在");
        }

        if ($goods['type'] == 1){
            $new_spu_info = [];

            if (!empty(json_decode($cart_info['spu_info'], true))){
                //将new_ku_sku_info键和值转成二维数组
                $new_spu_info = $spu_info;

                $item_name = "";
                $price = $goods['price'];
                if (!empty($new_spu_info)){
                    foreach ($new_spu_info as $v) {
                        if ($v['count']<=0){
                            continue;
                        }
                        $sku_item = SkuItem::get($v['spu_id']);
                        if (!$sku_item){
                            $item_name = $goods['title'].'/';
                        }else{
                            $sku_product = SkuProduct::where(["goods_id" => $goods_id, "key" => $v['spu_id']])->find();

                            $item_name .= $sku_item['name'] . '*'.$v['count'].'/';
                            $price = bcadd($price,bcmul($sku_product['price'], $v['count'], 2),2);
                        }
                    }
                    $item_name = substr($item_name, 0, -1);
                }
            }else{
                $item_name = "";
                $price = $goods['price'];
            }

            Cart::where([
                "user_id" => $user_id,
                "goods_id" => $goods_id,
                "spu_hash" => $cart_info['spu_hash'],
            ])->update([
                "item_name" => $item_name,
                "price" => $price,
                "spu_info" => json_encode($new_spu_info),
                "spu_info_ys" => json_encode($new_spu_info),
                "spu_hash" => md5(json_encode($new_spu_info)),
                "updatetime" => time(),
            ]);
        }else{
            //多规格
            if (!$item_id) {
                $this->error("规格不能为空");
            }


            //修改购物车
            $key = explode("_", $item_id);
            $item_name = "";
            foreach ($key as $v) {
                $item_name .= SkuItem::where(["id" => $v])->value("name") . '/';
            }
            $item_name = substr($item_name, 0, -1);
            $price = SkuProduct::where(["goods_id" => $goods_id, "key" => $item_id])->value("price");
            //增加此订单的购买数量
            Cart::where("id", $cart_info['id'])->update([
                "item_id"=> $item_id,
                "item_name" => $item_name,
                "price" => $price,
                "updatetime" => time(),
            ]);

        }


        $this->success("修改成功");

    }

    /*
     * 购物车列表
     */
    public function carList()
    {
        $user_id = $this->auth->id;
        $coupon_id = $this->request->post("coupon_id") ?? 0;
        $peopleCount = $this->request->post("peopleCount") ?? 0;
        $store_id = $this->request->post("store_id") ?? 0;
        $type = $this->request->post("type") ?? 1; //1 创建订单 2 加菜
        $data = Cart::with(["goods"])->where("user_id", $user_id)->where("store_id", $store_id)->where("status", "=", "0")->field("goods.title,goods.image")->select();
        $total = 0;
        foreach ($data as &$row) {
            if ($row->type == 1){
                $row->spu_info = json_decode($row->spu_info, true);
                $row->spu_info_ys = json_decode($row->spu_info_ys, true);
            }else{
                $row->spu_info = [];
                $row->spu_info_ys = [];
            }
            $row->score_id = $row->store_id;
            $total = bcadd($total, bcmul($row->count, $row->price, 2), 2);
            $row->hidden(["goods", "status"]);
        }

        $cwf_fee = 0;
        if ($peopleCount && $type==1) {
            if ($this->config['iscwf']) {
                $cwf_fee = bcmul($this->config['cwf'], $peopleCount, 2);
            }
        }

        if ($coupon_id > 1) {
            $coupon = Coupon::get($coupon_id);
            $after_total = bcadd(number_format($total - $coupon['used_amount'], 2), $cwf_fee, 2);

            if ($after_total <= 0) {
                $after_total = 0.01;
                if ($cwf_fee && $type == 1) {
                    $data = $data->toArray();
                    foreach ($data as &$v) {
                        $v['is_cw'] = 0;
                    }
                    array_push($data, ['title' => "餐位费", "price" => $cwf_fee, "image" => cdnurl("/assets/addons/fzdc/img/cwf.png", true), "count" => $peopleCount, "is_cw" => 1]);
                }
                $this->success("成功", ["data" => $data, "after_total" => $after_total, "total" => $total, "count" => count($data)]);
            }
        } else {
            $after_total = bcadd($total, $cwf_fee, 2);
        }
        if ($cwf_fee && $type == 1) {
            $data = $data->toArray();
            foreach ($data as &$v) {
                $v['is_cw'] = 0;
            }
            array_push($data, ['title' => "餐位费", "price" => $cwf_fee, "image" => cdnurl("/assets/addons/fzdc/img/cwf.png", true), "count" => $peopleCount, "is_cw" => 1]);
        }
        $this->success("成功", ["data" => $data, "after_total" => $after_total, "total" => $total, "count" => count($data)]);
    }

    /*
     * 清空购物车
     */
    public function empty()
    {
        $user_id = $this->auth->id;
        //查询当前用户下是否有购物车订单
        $res = Cart::where("user_id", $user_id)->select();
        if ($res->isEmpty()) {
            $this->error("购物车空空如也");
        }
        Cart::destroy(["user_id" => $user_id]);
        $this->success("清空成功");
    }

    /*
     * 购物车减少数量
     */
    public function reduce()
    {
        $user_id = $this->auth->id;
        $store_id = $this->request->post("store_id");    //门店id
        $cart_id = $this->request->post("cart_id");
        $goods_id = $this->request->post("goods_id");    //商品id
        $item_id = $this->request->post("spu_id");      //商品规格id
        $spu_info = $this->request->post("spu_info/a")??[];     //spu_info 单规格传
        $count = $this->request->post("count") ?? 0;       //商品数量
        //参数校验

        if (!$store_id || !$goods_id) {
            $this->error("请求参数不能为空");
        }

        if ($count == 0) {
            //清空购物车
            Cart::where(["user_id" => $user_id])->delete();
            $this->success("清空购物车成功");
        }
        $goods = Goods::get($goods_id);
        if ($goods['type'] == 1){
            if (!$cart_id){
                $this->error("购物车id不能为空");
            }

            $cart_info = Cart::get($cart_id);
            if (!$cart_info) {
                $this->error("购物车不存在");
            }
            if ($cart_info['count'] > 1) {
                //减少此订单的购买数量
                Cart::where("id", $cart_id)->where(["user_id" => $user_id])->setDec("count", $count);
            } else {
                $cart_info->delete();
            }
            $this->success("减少数量成功");

        }else{
            //先判断购物车是否有此订单
            $res = Cart::where(["store_id" => $store_id, "goods_id" => $goods_id, "item_id" => $item_id, "user_id" => $user_id])->find();
            if ($res) {
                if ($res['count'] > 1) {
                    //减少此订单的购买数量
                    Cart::where("id", $res['id'])->where(["user_id" => $user_id])->setDec("count", $count);
                } else {
                    $res->delete();
                }

            } else {
                $this->error("购物车内没有此订单");
            }
            $this->success("减少数量成功");
        }

    }

    /*
     * 加菜
     */
    public function jiac()
    {
        $userId = $this->auth->id;
        $id = $this->request->post('id');
        if (!$id) {
            $this->error("缺少订单id");
        }
        $order = Od::get($id);
        if (!$order) {
            $this->error("订单不存在");
        }
        $cartIds = Cart::where(["user_id" => $userId, "store_id" => $order['store_id']])->column("id");
        $price = 0;
        foreach ($cartIds as $v) {
            $cart = Cart::where(["id" => $v, "user_id" => $userId])->find();
            if (!$cart) {
                $this->error("没有此购物车数据");
            }
            if ($cart['item_id']){
                $stock = SkuProduct::where(["key" => $cart['item_id']])->value("stock");
                if ($stock < $cart['count']) {
                    //修改购物车状态
                    Cart::update(["status" => 1], ["id" => $cart['id'], "user_id" => $userId]);
                    $this->error("库存不足");
                }
                //减少库存
                SkuProduct::where(["key" => $cart['item_id']])->update(["stock" => $stock - $cart['count']]);
            }


            //查询次数
            $numbers = Detail::where(['order_id' => $id])->order("id", "desc")->value("numbers");
            $detail[] = [
                "user_id" => $userId,
                "order_id" => $id,
                "score_id" => $order['store_id'],
                "goods_id" => $cart['goods_id'],
                "goods_item_id" => $cart['item_id'],
                "goods_name" => Goods::where(["id" => $cart['goods_id']])->value("title"),
                "item_name" => $cart['item_name'],
                "goods_count" => $cart['count'],
                "goods_price" => $cart['price'],
                "goods_prices" => bcmul($cart['count'], $cart['price'],2),
                "numbers" => bcadd($numbers, 1),
            ];
            //订单价格
            $price = bcadd(bcmul($cart['count'], $cart['price'], 2), $price, 2);
        }
        $detailModel = new Detail();
        $detailModel->saveAll($detail);

        //判断订单状态
        if ($order['status'] == 1) {
            $order->order_amount_total = $order->order_amount_total + $price;
            $order->order_no = fzdc_orderNo($userId);
            $order->save();
        } else {
//            $order->status = 1;
            $order->order_no = fzdc_orderNo($userId);
            $order->d_amount_total = $price;
            $order->save();
        }

        //清空购物车
        Cart::where("id", "in", implode(',', $cartIds))->where(["user_id" => $userId])->delete();

        //打印订单
        $orderDetail = Detail::where(['order_id' => $id])->where("print_status",1)->find();
        //如果主订单已打印 则打印加菜订单
        if ($orderDetail){
            $this->print($order);
        }
        $store = Store::get($order['store_id']);
        $seat = Sear::get($order['seat_id']);

        //判断用户是否订阅消息推送
        Log::info("加菜推送消息开始");

        $userInfo_data = \app\admin\model\fzdc\store\User::where("store_id", $order['store_id'])->where("status", 'normal')->select();
        if ($userInfo_data){
            foreach ($userInfo_data as $v){
                $userInfo = Userdetail::get(['user_id'=>$v['user_id']]);

                if ($userInfo['subscribe'] == 1) {
                    Log::info("进入推送1");
                    $message = Push::where(["type" => 4])->find();
                    if ($message) {
                        Log::info("进入推送2");
                        if (!empty($message['multiplejson'])) {
                            $json = json_decode($message['multiplejson'], true);
                            //参数名对应订阅消息详细内容参数 （以下为测试）
                            $data = [];
                            foreach ($json as $jv) {
                                switch ($jv['title']) {
                                    case '14':
                                        $data['data'][$jv['keyword']]['value'] = $store['title'];
                                        break;
                                    case '15':
                                        $data['data'][$jv['keyword']]['value'] = (int)$seat['no'];
                                        break;
                                    case '16':
                                        $data['data'][$jv['keyword']]['value'] = "已加菜";
                                        break;
                                    case '17':
                                        $data['data'][$jv['keyword']]['value'] = $price;
                                        break;

                                }
                            }
                            Log::info("加菜推送数据：" . json_encode($data['data']));
                            $data['order_id'] = $order['id'];
                            $data['openid'] = $userInfo['openid'];
                            $data['masterplate'] = $message->masterplate;
                            Queue::later(2, 'addons\fzdc\job\SendMessage', $data, 'dcOrderQueue');
                        }

                    }
                }
            }
        }


        $this->success("加菜成功");
    }

    /*
     * 生成订单
     */
    public function create()
    {
        $userId = $this->auth->id;
        $type = $this->request->post('type') ?? 1;         // 订单状态 1=支付订单 2=充值订单
        $dc_type = $this->request->post('dc_type') ?? 1;         // 点餐类型:1=用户点餐,2=门店点餐
        $recharge_id = $this->request->post('recharge_id');     // 充值id
        $orderType = $this->request->post('orderType') ?? 0;    // 订单类型 1自取 2外卖 3=堂食 0=暂无
        $storeId = $this->request->post('storeId')??0;         // 店铺id
        $seatId = $this->request->post('seatId/a');          // 桌号id
        $subscribeTime = $this->request->post('subscribeTime');   // 预约时间
        $subscribeTel = $this->request->post('subscribeTel');    // 预留电话
        $serviceTime = $this->request->post('serviceTime');     // 送达时间
        $addressId = $this->request->post('addressId') ?? 0;    // 收货地址ID
        $remark = $this->request->post('remark') ?? '';      // 订单备注
        $couponId = $this->request->post('couponId') ?? 0;     // 优惠券ID
        $tablewareCount = $this->request->post('tablewareCount');  // 餐具数量
        $pType = $this->request->post('pType') ?? 1;        // 支付类型 1=先付后餐 2=先餐后付
        $peopleCount = $this->request->post('peopleCount') ?? null;     // 就餐人数

        if ($type == 1){
            //判断是否在范围内
            $store = Store::get($storeId);
            if ($orderType == 2){
                if (!$store['radius']){
                    $this->error("当前区域不在配送范围,请更换收货地址");
                }else{
                    $address = Address::get($addressId);
                    if (!$address){
                        $this->error("收货地址不存在");
                    }
                    $lat = $address['lat'];
                    $lon = $address['lon'];
                    if (!$lat ||!$lon){
                        $this->error("收货地址经纬度为空,请重新设置收货地址");
                    }

                    $distance = fzdc_get_distance([$store['lon'],$store['lat']],[$lon,$lat],true,2);
                    if ($distance > $store['radius']){
                        $this->error("当前区域不在配送范围,请更换收货地址");
                    }
                }
            }

            $is_business = 0;
            $startTime = $store['start_times'];
            $endTime = $store['end_times'];
            $currentTime = date("H:i:s");
            if ($endTime < $startTime) {
                if ($currentTime >= $startTime || $currentTime < $endTime) {
                    $is_business = 1;
                }
            } else {
                if ($currentTime >= $startTime && $currentTime < $endTime) {
                    $is_business = 1;
                }
            }

            if (!$is_business) {
                $this->error("该门店歇业中");
            }
        }


        
        $address_info = "";
        // if ($dc_type == 1){
        //     //门店店员不允许前台点餐
        //     $u = \app\admin\model\fzdc\store\User::where(['user_id' => $userId,'store_id' => $storeId,'status'=>'normal'])->find();
        //     if ($u){
        //         $this->error("门店店员不允许前台点餐");
        //     }
        // }

        Log::info("seatId:".json_encode($seatId));

        $info = get_addon_info('epay');
        if (empty($info)) {
            $this->error("请先安装微信支付宝整合插件");
        }
        $open_id = Userdetail::get(["user_id" => $userId]);
//        if (!$open_id['openid'] && $dc_type == 1) {
//            $this->error("请先绑定微信", [], "402");
//        }
        //去重$seatId

        if ($seatId){
            $seatId = array_unique($seatId);

            //查询当前桌号是否有未付款的订单 如果有 则不能创建订单
            foreach ($seatId as $sv){
                $order = Od::where(['status' => 1,"order_type"=>3])->where("FIND_IN_SET('{$sv}', seat_id)")->find();
                if ($order) {
                    $this->error("该桌号有未付款订单");
                }
                $seat = Sear::get($sv);
                if(isset($seat['status'])){
                    if ($seat['status'] != 'normal'){
                        $this->error("桌号状态不正确");
                    }
                    if ($seat['use_status']==2){
                        $this->error("桌号正在使用中");
                    }

                }
            }

        }

        //字段校验
        if ($type == 1) {
            if (empty($storeId)) {
                $this->error("店铺id不能为空");
            }
            $cartIds = Cart::where(["user_id" => $userId, "store_id" => $storeId])->column("id");

            if ($orderType == 1) {
                if (empty($subscribeTime)) {
                    $this->error("预约时间不能为空");
                }
                if (empty($subscribeTel)) {
                    $this->error("预留电话不能为空");
                }
            } elseif ($orderType == 2) {
                if (empty($serviceTime)) {
                    $this->error("送达时间不能为空");
                }
                if (empty($addressId)) {
                    $this->error("收货地址不能为空");
                }else{
                    $address_info = Ad::where("id", $addressId)->find();
                    if (!$address_info){
                        $this->error("收货地址不存在");
                    }
                    $address_info["title"]=$address_info['title'];
                    $address_info["mobile"]=$address_info['mobile'];
                    $address_info["suffix"]=$address_info['suffix'];
                    $address_info["remark"]=$address_info['remark'];
                    $address_info["tag"]=$address_info['tag'];
                    $address_info["isDefault"]=$address_info['isDefault'];
                    $address_info = json_encode($address_info);

                }
                if (empty($tablewareCount)) {
                    $this->error("餐具数量不能为空");
                }
            } else {
                if (empty($seatId)) {
                    $this->error("桌号不能为空");
                }
            }

            if ($subscribeTime == "立即就餐") {
                $subscribeTime = time();
            }

            if ($serviceTime == "立即就餐") {
                $serviceTime = time();
            }

            if (!in_array($orderType, [1, 2, 3])) {
                $this->error("订单类型有误");
            }
            //先餐后付 订单不预先使用优惠券
            if ($pType == 2) {
                $couponId = 0;
            }
            if ($couponId != 0) {
                //查看优惠券是否可以使用
                $receive = Receive::get(["user_id" => $userId, "coupon_id" => $couponId]);
                if (!$receive) {
                    $this->error("优惠券信息不存在");
                }
                if ($receive['state'] == 1 || $receive['state'] == -1) {
                    $this->error("优惠券状态不正确");
                }
                //查询优惠券是否在可用时间内
                $coupon = Coupon::get($couponId);
                if (time() < $coupon->start_time || time() > $coupon->end_time) {
                    $this->error("优惠券已过可用时间");
                }
            }
            //判断库存
            $price = 0;
            foreach ($cartIds as $v) {
                $cart = Cart::where(["id" => $v, "user_id" => $userId])->find();
                if (!$cart) {
                    $this->error("没有此购物车数据");
                }
                if (!empty($cart['item_id'])){
                    $stock = SkuProduct::where(["key" => $cart['item_id']])->value("stock");
                    if ($stock < $cart['count']) {
                        //修改购物车状态
                        Cart::update(["status" => 1], ["id" => $cart['id'], "user_id" => $userId]);
                        $this->error("库存不足");
                    }
                    //减少库存
                    SkuProduct::where(["key" => $cart['item_id']])->update(["stock" => $stock - $cart['count']]);
                }

                //订单价格
                $price = bcadd(bcmul($cart['count'], $cart['price'], 2), $price, 2);
            }

            //计算实际付款金额
            if ($couponId != 0) {
                //查询优惠券满减金额
                $coupon = Coupon::where("id", $couponId)->field("used_amount")->find();
                $endPrice = bcsub($price, $coupon['used_amount'], 2);
                if ($endPrice <= 0) {
                    $endPrice = 0.01;
                }
            } else {
                if ($price <= 0) {
                    $endPrice = 0.01;
                } else {
                    $endPrice = $price;

                }
            }
            $in_cartIds = implode(',', $cartIds);
            $recharge = 0;
        } else {
            if (empty($recharge_id)) {
                $this->error("充值id不能为空");
            }
            $recharge = Recharge::get($recharge_id);
            if (!$recharge) {
                $this->error("数据异常");
            }
            $endPrice = $recharge['amount'];
            $in_cartIds = "";
            $recharge = $recharge['amount_over'] - $recharge['amount'];
            $cartIds = "";
        }

        $orderNo = fzdc_orderNo($userId);
        $cwf_fee = 0;
        if ($peopleCount) {
            if ($this->config['iscwf']) {
                $cwf_fee = bcmul($this->config['cwf'], $peopleCount, 2);
                $endPrice = bcadd($endPrice, $cwf_fee,2);
            }
        }
        if ($type == 2) {
            $orderType = 0;
        }
        $business_status = 0;
        if ($orderType == 3){
            $business_status = 1;
        }
        $status = 1;
        
        if ($pType == 2){
            $status = 6;
        }

        $data = [
            "order_no" => $orderNo,            //订单编号
            "order_type" => $orderType,          //订单类型
            "type" => $type,               //订单类型
            "user_id" => $dc_type==2? $storeId :$userId,             //用户id
            "store_id" => $storeId,            //门店id
            "address_id" => $addressId,          //收货地址id
            "coupon_id" => $couponId,           //优惠券id
            "status" => $status,                   //订单状态
            "business_status" => $dc_type==2?2:$business_status,                   //商家接单状态
            "order_amount_total" => $endPrice,           //实际付款金额
            "remark" => $remark,             //订单备注
            "tableware_count" => $tablewareCount,     //餐具数量
            "subscribe_time" => $subscribeTime,      //预约时间
            "subscribe_tel" => $subscribeTel,       //预留电话
            "service_time" => $serviceTime,        //送达时间
            "cart_ids" => $in_cartIds,         //选择的购物车商品
            "seat_id" => empty($seatId)? "" : implode(',', $seatId),             //桌号id
            "recharge" => $recharge,           //充值赠送金额
            "p_type" => $dc_type==2?2:$pType,              //支付类型
            "people_count" => $peopleCount,        //就餐人数
            "cwf_fee" => $cwf_fee,            //餐位费
            "dc_type" => $dc_type,
            "address_info" => $address_info,
        ];

        //取餐号
        if ($orderType == 1) {
            $zm = "Z";
        } elseif ($orderType == 2) {
            $zm = "W";
        } else {
            $zm = "T";
        }
        if ($type == 2) {
            $zm = "C";
        }
        $order = Od::where(["order_type" => $orderType])->whereTime("createtime", "today")->order("id", "desc")->find();
        if ($order) {
            $code = substr($order['code'], 1);
            $data['code'] = $zm . bcadd($code, 1);
        } else {
            $data['code'] = $zm . "1";
        }

        $detail = [];
        //数据入库
        Db::startTrans();
        try {

            //插入订单详情表
            if ($cartIds || $type == 2) {

                ModelUser::update(["is_order" => 1], ["id" => $userId]);
                //插入订单表
                $result = Od::create($data);
                if ($seatId){
                    //更新桌号状态
                    Sear::update(["use_status"=>2],["id"=>["in",$seatId]]);
                }
                if ($cartIds){
                    $carts = Cart::where("id", "in", implode(',', $cartIds))->where(["user_id" => $userId])->select();
                    if (!$carts->isEmpty()) {
                        foreach ($cartIds as $k => $v) {
                            $info = Cart::where(["id" => $v, "user_id" => $userId])->find();
                            if ($info) {
                                $detail[] = [
                                    "user_id" => $userId,
                                    "order_id" => $result->id,
                                    "score_id" => $info['store_id'],
                                    "goods_id" => $info['goods_id'],
                                    "goods_item_id" => $info['item_id'],
                                    "goods_name" => Goods::where(["id" => $info['goods_id']])->value("title"),
                                    "item_name" => $info['item_name'],
                                    "goods_count" => $info['count'],
                                    "goods_price" => $info['price'],
                                    "spu_info" => $info['type']==1? $info['spu_info']:[],
                                    "goods_prices" => $info['type']==1? $info['price'] : bcmul($info['count'], $info['price'],2),
                                ];
                            }
                        }
                        $detailModel = new Detail();
                        $detailModel->saveAll($detail);
                    } else {
                        throw new Exception("购物车数据为空");
                    }
                    //清空购物车
                    Cart::where("id", "in", implode(',', $cartIds))->where(["user_id" => $userId])->delete();
                }



                //插入佣金明细未入账
                $udetail = Userdetail::get(['user_id' => $userId]);
                if ($udetail->parent_id != 0) {
                    //根据上级代理等级抽取佣金
                    $grade = Userdetail::where("user_id", $udetail->parent_id)->value('proxy_level');
                    $info = $this->commission($endPrice, $grade);
                    $this->addCommission($info, $result->id, $endPrice, $udetail, 1);
                    //上上级同样抽取佣金
                    $luser = Userdetail::get(["user_id" => $udetail->parent_id]);
                    if ($luser['parent_id'] != 0) {
                        $grade = Userdetail::where("user_id", $luser['parent_id'])->value('proxy_level');
                        $info = $this->commission($endPrice, $grade);
                        $this->addCommission($info, $result->id, $endPrice, $luser, 2);
                    }

                }

                //更新优惠券为已使用
                if ($couponId) {
                    Receive::update(['state' => 1], ['user_id' => $userId, 'coupon_id' => $couponId]);
                }
            } else {
                throw new Exception("请至少选择一件商品");

            }


            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            Log::error("订单创建失败:". $e->getMessage(). " Line:". $e->getLine());
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($orderType!=3){
            //订单放入队列 处理超时取消
            $data = ["orderNo" => $orderNo, "type" => 1];
            Queue::later(bcmul($this->config['timeout'], 60), 'addons\fzdc\job\Overtime', $data, 'dcOrderQueue');
        }

        if ($pType == 2){
            //打印订单
            $order = Od::get(['order_no' => $orderNo]);
            $this->print($order);
        }


        $this->success("成功", ["orderNo" => $orderNo]);

    }

    //佣金明细
    public function commission($amount, $grade)
    {
        $info = \app\admin\model\fzdc\distribution\Grade::get($grade);
        return [
            "one_amount" => bcmul($amount, bcdiv($info['one_level'], 100, 2), 2),
            "two_amount" => bcmul($amount, bcdiv($info['two_level'], 100, 2), 2),
        ];

    }

    //增加佣金明细
    public function addCommission($info, $orderId, $pay_amount, $userInfo, $flag = 1)
    {
        Db::startTrans();
        try {
            $pid = $userInfo->parent_id;
            if ($flag == 1) {
                $amound = bcadd($info['one_amount'], 0, 2);
            } else {
                $amound = bcadd($info['two_amount'], 0, 2);
            }
            \app\admin\model\fzdc\distribution\Log::create([
                "user_id" => $pid,
                "pay_user_id" => $this->auth->id,
                "order_id" => $orderId,
                "pay_amount" => $pay_amount,
                "distribution_amount" => $amound,
                "createtime" => time(),
            ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
        }
    }

    /*
     * 发起支付
     */
    public function pay()
    {
        $info = get_addon_info('epay');
        if (empty($info)) {
            $this->error("请先安装微信支付宝整合插件");
        }
        $orderNo = $this->request->post('orderNo'); //订单编号
        $payType = $this->request->post('payType') ?? 1; //支付方式 1=微信 2=钱包
        if (!$orderNo) {
            $this->error("请输入订单编号");
        }
        //判断是否有open_id
        $user_id = $this->auth->id;
        $open_id = Userdetail::get(["user_id" => $user_id]);
        if ($payType == 1){
            if (!$open_id['openid']) {
                $this->error("请先绑定微信", [], "402");
            }
        }

        //判断订单状态
        $order = Od::get(['order_no' => $orderNo]);
        if (!$order) {
            $this->error("订单不存在");
        }
        if ($order['status'] == 5) {
            $this->error("该订单已取消，请重新下单");
        }
        if (in_array($order['status'], [2, 3, 4, 5])) {
            $this->error("订单状态不正确");
        }
        $user = \app\admin\model\User::get($user_id);
        if ($payType == 1) {
            //调用微信支付
            $detail = Detail::where(["order_id" => $order['id']])->select();
            $str = "";
            foreach ($detail as $v) {
                $str .= $v['goods_name'] . ',';
            }
            $str = $user['username'] . " " . substr($str, 0, -1);
            if ($order['order_type'] == 4) {
                $str = $user['username'] . " 预约定金";
            }

            $params = [
                'amount' => $order['order_amount_total'],
                'orderid' => $order['order_no'],
                'type' => "wechat",
                'title' => $str,
                'notifyurl' => request()->domain() . "/addons/fzdc/order/notifyx",
                'returnurl' => "",
                'method' => "miniapp",
                'openid' => $open_id['openid'],
            ];
            $result = Service::submitOrder($params);
            $order->pay_type = 1;
            $order->save();

            $this->success('成功', $result);
        } else {
            //判断余额
            if ($user['money'] < $order['order_amount_total']) {
                $this->error("余额不足");
            }
            $user->money = $user['money'] - $order['order_amount_total'];
            $user->save();
            $order->pay_type = 2;

            //分销
            Log::info("钱包支付分销");
            $no = $order->order_no;
            Hook::listen('fzdc_distribution', $no);

            if ($order['seat_id'] && $order['p_type'] == 2){
                //变更桌号状态
                Sear::whereIn("id", $order['seat_id'])->update(["use_status"=> 3]);
                //放入队列 处理状态释放
                $data = ["seat_id" => $order['seat_id'], "type" => 3];
                Queue::later(bcmul($this->config['clean_time'], 60), 'addons\fzdc\job\Overtime', $data, 'dcOrderQueue');
            }

            if ($order->order_type == 4) {
                $order->status = 10;
                //订单放入队列 超过预约时间自动变成已完成
                $data = ["orderNo" => $order['order_no'], "type" => 2];
                $later_time = $order['subscribe_time']-time();
                Queue::later($later_time, 'addons\fzdc\job\Overtime', $data, 'dcOrderQueue');
                //到预约时间桌号自动变成使用中
                Queue::later($order['subscribe_time']-time(), 'addons\fzdc\job\Overtime', ["orderNo" => $order['order_no'], "type" => 4], 'dcOrderQueue');
            } else {
                $order->status = 6;
                if ($order->order_type == 3){
                    $order->business_status = 2;
                }else{
                    $order->business_status = 1;
                }

                //异步推送消息
                //判断用户是否订阅消息推送
                $userInfo = Userdetail::get(["user_id" => $order->user_id]);
                Log::info("推送消息开始");
                if ($userInfo['subscribe'] == 1) {
                    Log::info("进入推送1");
                    $message = Push::where(["type" => 1])->find();
                    if ($message) {
                        Log::info("进入推送2");
                        if (!empty($message['multiplejson'])) {
                            $json = json_decode($message['multiplejson'], true);
                            //参数名对应订阅消息详细内容参数 （以下为测试）
                            $data = [];
                            foreach ($json as $jv) {
                                switch ($jv['title']) {
                                    case '1':
                                        $data['data'][$jv['keyword']]['value'] = $this->config['share_title'];
                                        break;
                                    case '2':
                                        $data['data'][$jv['keyword']]['value'] = $order->order_no;
                                        break;
                                    case '3':
                                        $data['data'][$jv['keyword']]['value'] = $order->order_amount_total;
                                        break;
                                    case '4':
                                        $data['data'][$jv['keyword']]['value'] = date("Y-m-d H:i:s", time());
                                        break;

                                }
                            }
                            //Log::info("推送数据：" . json_encode($data['data']));
                            $data['order_id'] = $order['id'];
                            $data['openid'] = $userInfo['openid'];
                            $data['masterplate'] = $message->masterplate;
                            Queue::later(2, 'addons\fzdc\job\SendMessage', $data, 'dcOrderQueue');
                        }

                    }

                }

            }
            $order->pay_time = time();
            $order->save();
            $m_memo = "订餐减少余额";
            MoneyLog::create(['user_id' => $user_id, 'money' => $order['order_amount_total'], 'before' => $user['money'], 'after' => $user['money'] - $order['order_amount_total'], 'memo' => $m_memo]);



            $store = Store::get($order['store_id']);
            $store->setInc("balance", $order['order_amount_total']);
            $store->save();
            //增加商家收入明细
            Revenue::create(["store_id" => $order['store_id'], "type" => 1,"pay_type"=>2, "amount" => $order['order_amount_total'], "user_id" => $order['user_id'], "createtime" => time(), "updatetime" => time()]);
            $this->print($order);
            $this->success('成功');
        }

    }

    /*
     * 获取餐具数据
     */
    public function tableware()
    {
        $data = $this->config['tableware'];
        if (is_string($data)) {
            $data = explode(',', $data);
        }
        foreach ($data as &$v) {
            if ($v == 0) {
                $v = "无需餐具";
            } else {
                $v = $v . "人份";
            }
        }
        $this->success("成功", ['tableware' => $data]);
    }

    /*
     * 当前订单
     */
    public function current(){
        $user_id = $this->auth->id;
        $seat_id = $this->request->post('seat_id');  //当前桌号
        $where = [];
        if ($seat_id){
            $seat = Sear::get($seat_id);
            if (!$seat) {
                $this->error("桌号不存在");
            }
//            $where['order_type'] = ['in',[3]];
        }else{
//            $where['order_type'] = ['in',[1,2]];
            $where['user_id'] = ['=',$user_id];

        }

        $where['dc_type'] = ['=',1];
        $where['status'] = ['in',[1,2,4,6,7,8,10]];
        if ($seat_id){
            $order = Od::where("FIND_IN_SET('{$seat_id}', seat_id)")->whereTime("createtime", "today")->where($where)->order("id", "desc")->find();
            //如果当前桌号没有订单，则取自己的订单
            if (!$order) {
                $order = Od::where(["user_id" => $user_id])->whereTime("createtime", "today")->where($where)->order("id", "desc")->find();
            }
        }else{
            $order = Od::where($where)->whereTime("createtime", "today")->order("id", "desc")->find();
        }
        if (!$order) {
            $this->error("当前无订单");
        }
        if (isset($seat)) {
            if ($seat['img']) {
                $order['seat_img'] = cdnurl($seat['img'], true);
            } else {
                $order['seat_img'] = "";
            }
            $order['seat_title'] = $seat['title'];
            $order['seat_no'] = $seat['no'];
        } else {
            $order['seat_img'] = "";
            $order['seat_title'] = "";
            $order['seat_no'] = "";
        }
        $score_id = Detail::where("order_id", $order['id'])->limit(1)->value("score_id");
        $order['store_id'] = $score_id;
        $order['store'] = \app\admin\model\fzdc\store\Store::Where("id", $score_id)->value("title");
        $order['detail'] = Detail::where("order_id", $order['id'])->field("goods_name as title,score_id,goods_price as price,goods_id,item_name,goods_count as count,numbers")->select()->each(function ($it) use($order) {
            $it->image = Goods::where(["id" => $it->goods_id])->value("image");
            $it->type = $order['type'];
            if ($it->numbers>1){
                $it->numbers = 2;
            }
        });
        if ($order['order_type'] == 3 && $order['detail']){
            $o_d = $order['detail']->toArray();
            array_push($o_d, ["title"=>"餐位费","price"=>$order['cwf_fee'],"count"=>$order['people_count'],"image"=>cdnurl('/assets/addons/fzdc/img/cwf.png', true),"numbers"=>1]);
            $order['detail'] = $o_d;
        }
        $order['heg'] = '320rpx';

        $this->success("成功", $order);

    }

    /*
     * 历史订单
     */
    public function list()
    {
        $user_id = $this->auth->id;
        $page = $this->request->post('page') ?? 1;  //页码
        $limit = $this->request->post('limit') ?? 10; //每页显示条数
        $type = $this->request->post('type');
        $types = $this->request->post('types') ?? 1;
        $status = $this->request->post('status');
        $time = $this->request->post('time') ?? "";
        $start_time = $this->request->post('start_time') ?? "";
        $end_time = $this->request->post('end_time') ?? "";

//        var_dump($user_id);die;
        $where = [];
        $where['user_id'] = $user_id;
        $where['dc_type'] = ['=',1];
        if (!empty($time)) {
            $start_time1 = strtotime($time . " 00:00:00");
            $end_time1 = strtotime($time . " 23:59:59");
            $where['createtime'] = ["between time", [$start_time1, $end_time1]];
        }
        if (!empty($start_time) && !empty($end_time)) {
            $start_time = strtotime($start_time . " 00:00:00");
            $end_time = strtotime($end_time . " 23:59:59");
            $where['createtime'] = ["between time", [$start_time, $end_time]];
        }
        if ($status) {
            $where['status'] = ["=", $status];
        }
        if ($type) {
            $where['order_type'] = $type;
        }
        if ($types) {
            $where['type'] = $types;

        }
        $list = Od::where($where)->whereIn("status", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])->field("id,order_no,status,order_type as type,order_amount_total,createtime,seat_id,subscribe_name,dd_time,subscribe_time,subscribe_tel,people_count,cwf_fee,user_id")->order("id", "desc")->paginate(["page" => $page, "list_rows" => $limit])->each(function ($item) {
            $score_id = Detail::where("order_id", $item->id)->limit(1)->value("score_id");
            if ($item->seat_id) {
                $seat = Sear::whereIn('id',$item->seat_id)->select();
                $seat_info = [];
                if ($seat) {
                    foreach ($seat as $sk => $s){
                        $seat_info[$sk]['seat_title'] = $s['title'];
                        $seat_info[$sk]['seat_no'] = $s['no'];
                        if ($s['img']) {
                            $seat_info[$sk]['seat_img'] = cdnurl($s['img'], true);
                        } else {
                            $seat_info[$sk]['seat_img'] = "";
                        }
                    }
                }
                $item->seat_info = $seat_info;

            }
            $item->store_id = $score_id;
            $item->store = \app\admin\model\fzdc\store\Store::Where("id", $score_id)->value("title");
            $item->detail = Detail::where("order_id", $item->id)->field("goods_name as title,score_id,goods_price as price,goods_id,item_name,goods_count as count,numbers")->select()->each(function ($it) use ($item) {
                $it->image = Goods::where(["id" => $it->goods_id])->value("image");
                $it->type = $item->type;
                if ($it->numbers>1){
                    $it->numbers = 2;
                }
            });
            if ($item->type == 3 && $item->detail){
                $o_d = $item->detail->toArray();
                if ($item->cwf_fee>0){
                    array_push($o_d, ["title"=>"餐位费","price"=>$item->cwf_fee,"count"=>$item->people_count,"image"=>cdnurl('/assets/addons/fzdc/img/cwf.png', true),"numbers"=>1]);
                }
                $item->detail = $o_d;
            }
            $item->heg = '320rpx';
            if (empty($item->subscribe_tel)){
                $item->subscribe_tel = \app\admin\model\fzdc\user\User::where("id", $item->user_id)->value("mobile");
            }
        });
        $this->success("成功", $list);
    }

    /*
     * 订单详情
     */
    public function detail()
    {
        $user_id = $this->auth->id;
        $orderId = $this->request->post('order_id');
        if (!$orderId) {
            $this->error("缺少订单id");
        }
        $res = Od::get($orderId);
        if (!$res) {
            $this->error("订单不存在");
        }
        if ($res['order_type']==3){
            $else_user = Detail::where(["order_id" => $orderId])->column('user_id');
            // if (!in_array($user_id, $else_user)){
            //     $this->error("无权查看");
            // }
            $list = Od::where(["id" => $orderId])->field("id,order_no,store_id,remark,address_id,order_type,code,subscribe_time,status,pay_type,pay_time,order_amount_total,createtime,seat_id,subscribe_tel,subscribe_name,dd_time,people_count,cwf_fee")->find();
        }else{
            $list = Od::where(["user_id" => $user_id, "id" => $orderId])->field("id,order_no,store_id,remark,address_id,order_type,code,subscribe_time,status,pay_type,pay_time,order_amount_total,createtime,seat_id,subscribe_tel,subscribe_name,dd_time,people_count,cwf_fee")->find();
        }

        $score_id = Detail::where("order_id", $list['id'])->limit(1)->value("score_id");
        if (!$score_id) {
            $score_id = $list['store_id'];
        }
        $store = \app\admin\model\fzdc\store\Store::Where("id", $score_id)->find();
        if($store){
            $list['store'] = $store["title"];
            $list['lon'] = $store["lon"];
            $list['lat'] = $store["lat"];
            $list['tel'] = $store["tel"];
        }
        // $list['store'] = $store["title"];
        // $list['lon'] = $store["lon"];
        // $list['lat'] = $store["lat"];
        // $list['tel'] = $store["tel"];
        if ($list['address_id']) {
            $address_info = \app\admin\model\fzdc\Address::get($list['address_id']);
            if ($address_info) {
                $list['address'] = $address_info['title'] . " " . $address_info['mobile'] . " " . $address_info['address'] . " " . $address_info['remark'];
            } else {
                $list['address'] = "";

            }
        }
        if ($list['status'] == 1) {
            $end_time = bcadd($list['createtime'], bcmul($this->config['timeout'], 60));
            if (time() > $end_time) {
                $list['end_time'] = 0;
            } else {
                $list['end_time'] = bcsub($end_time, $list['createtime']) * 1000;
            }

        }

        if ($list['order_type'] == 4 || $list['order_type'] == 3 || $list['seat_id']) {
            $seat = Sear::whereIn('id',$list['seat_id'])->select();
            $seat_info = [];
            if ($seat) {
                foreach ($seat as $sk => $s){
                    $seat_info[$sk]['seat_title'] = $s['title'];
                    $seat_info[$sk]['seat_no'] = $s['no'];
                    if ($s['img']) {
                        $seat_info[$sk]['seat_img'] = cdnurl($s['img'], true);
                    } else {
                        $seat_info[$sk]['seat_img'] = "";
                    }
                }
            }
            $list['seat_info'] = $seat_info;
        }

        $list['tel'] = isset($store["tel"]) ? $store["tel"] : '';
        $list['detail'] = Detail::where("order_id", $list['id'])->field("goods_name as title,goods_id,item_name,goods_count as count,goods_price as price,numbers")->select()->each(function ($it) {
            $it->image = Goods::where(["id" => $it->goods_id])->value("image");
            if ($it->numbers>1){
                $it->numbers = 2;
            }
        });
        $list['subscribe_time'] = intval($list['subscribe_time']);
        $list['cwf_img'] = cdnurl('/assets/addons/fzdc/img/cwf.png', true);
        $this->success("成功", $list);
    }

    /*
     * 取消订单
     */
    public function cancel()
    {
        $user_id = $this->auth->id;
        $orderId = $this->request->post('order_id');
        if (!$orderId) {
            $this->error("缺少订单id");
        }
        $res = Od::get(["id" => $orderId, "user_id" => $user_id]);

        if (!$res) {
            $this->error("订单不存在");
        }
        if (in_array($res['status'], [2, 3, 4, 5, 7, 8])) {
            $this->error("订单状态已发生变更,不可取消");
        }
        //判断是否有优惠券
        if ($res['coupon_id'] > 0) {
            //更新优惠券为未使用，判断优惠券是否过期
            $coupon = Coupon::get($res['coupon_id']);
            if (time() > $coupon->end_time) {
                $res5 = Receive::update(['state' => -1], ["user_id" => $res['user_id'], "coupon_id" => $res['coupon_id']]);
            } else {
                $res5 = Receive::update(['state' => 0], ["user_id" => $res['user_id'], "coupon_id" => $res['coupon_id']]);
            }
            Log::log("优惠券更新状态" . $res5);
        }
        $res->status = 5;
        $res->save();
        //增加库存
        if ($res['cart_ids']) {
            $ids = Detail::where(['order_id' => $res['id']])->column('id');
            foreach ($ids as $v) {
                $detail = Detail::where(["id" => $v])->find();
                $sku = SkuProduct::get(["key" => $detail['goods_item_id']]);
                if ($sku) {
                    $sku->setInc("stock", $detail['goods_count']);
                }
            }
        }
        if ($res['seat_id']){
            $seat_id = explode(',',$res['seat_id']);
            foreach ($seat_id as $v){
                Sear::where("id", $v)->update(['use_status'=>1]);
            }
        }
        //清除购物车数据
        Cart::where("id", "in", $res['cart_ids'])->delete();
        //清除分销明细待入账数据
        DL::where(['order_id'=>$orderId,'status'=>1])->delete();
        $this->success("订单取消成功");
    }

    /*
     * 确认收货
     */
    public function confirm()
    {
        $user_id = $this->auth->id;
        $orderId = $this->request->post('order_id');
        if (!$orderId) {
            $this->error("缺少订单id");
        }
        $res = Od::get(["order_no" => $orderId, "user_id" => $user_id]);
        if (!$res) {
            $this->error("订单不存在");
        }
        if (in_array($res['status'], [1, 3, 4, 5])) {
            $this->error("订单状态错误");
        }
        $res->status = 3;
        $res->confirm_time = time();
        $res->save();
        //清除购物车数据
        Cart::where("id", "in", $res['cart_ids'])->delete();
        $this->success("订单已确认收货");
    }

    /*
     * 支付成功回调
     */
    public function notifyx()
    {
        Log::info("进入支付回调通知");
        $config = get_addon_config('fzdc');
        $type = $this->request->param('type') ?? 'wechat';
        Log::info("【支付成功】type:" . $type);
        $pay = \addons\epay\library\Service::checkNotify($type);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        Log::info("回调开始");
        if ($data['result_code'] == "SUCCESS") {
            Log::info("支付成功");
            Db::startTrans();
            try {
                $order = \app\admin\model\fzdc\order\Order::get(["order_no" => $data['out_trade_no']]);
                if ($order['status'] != 1){
                    return $pay->success()->send();
                }
                //打印订单
                $business_status = 0;

                if ($order['seat_id'] && $order['p_type'] == 2){
                    //变更桌号状态
                    Sear::whereIn("id", $order['seat_id'])->update(["use_status"=> 3]);
                    //放入队列 处理状态释放
                    $data = ["seat_id" => $order['seat_id'], "type" => 3];
                    Queue::later(bcmul($this->config['clean_time'], 60), 'addons\fzdc\job\Overtime', $data, 'dcOrderQueue');
                }

                if ($order['type'] == 1) {
                    $store = Store::get($order['store_id']);
                    $store->setInc("balance", $order['order_amount_total']);
                    $store->save();
                    //增加收入明细
                    Revenue::create(["store_id" => $order['store_id'], "type" => 1,"pay_type"=>$order['pay_type'], "amount" => $order['order_amount_total'], "user_id" => $order['user_id'], "createtime" => time(), "updatetime" => time()]);
                    if ($order['p_type']==1  && get_addon_config('fzdc')['xpprint'] == 1){
                        $this->print($order);
                    }
                    //清除购物车
                    Cart::where("id", "in", $order['cart_ids'])->delete();
                    $memo = "购买餐品增加积分";
                } else {
                    $memo = "充值增加积分";
                    $m_memo = "充值增加余额";
                    //增加用户余额
                    \app\common\model\User::money($order['order_amount_total'] + $order['recharge'], $order['user_id'], $m_memo);
                }
                //订单类型
                Log::info("订单类型：". $order['order_type']);
                if ($order['order_type'] == 4) {
                    Log::info("进入2");
                    $status = 10;
                    //订单放入队列 超过预约时间自动变成已完成
                    $data = ["orderNo" => $order['order_no'], "type" => 2];
                    $later_time = $order['subscribe_time']-time();
                    Queue::later($later_time, 'addons\fzdc\job\Overtime', $data, 'dcOrderQueue');
                    //到预约时间桌号自动变成使用中
                    Queue::later($order['subscribe_time']-time(), 'addons\fzdc\job\Overtime', ["orderNo" => $order['order_no'], "type" => 4], 'dcOrderQueue');
                } elseif($order['order_type']==3) {
                    Log::info("进入3");
                    $status = 6;
                    $business_status = 2;
                }else{
                    Log::info("进入1");
                    $status = 6;
                    $business_status = 1;
                }
                $res = \app\admin\model\fzdc\order\Order::update(["status" => $status, "business_status" => $business_status, 'out_trade_no' => $data['transaction_id'], "pay_time" => time()], ["order_no" => $data['out_trade_no']]);
                Log::info("修改订单状态结果" . $res);

                //取系统默认赠送积分数
                $points = $config['default_points'];
                \app\common\model\User::score($points, $order['user_id'], $memo);
                Log::info("增加积分结束");
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                Log::error($e->getMessage());
                return "error";
            }

            //分销
            Log::info("微信支付分销");
            $no = $data['out_trade_no'];
            Hook::listen('fzdc_distribution', $no);

            //异步推送消息
            //判断用户是否订阅消息推送
            $userInfo = Userdetail::get(["user_id" => $order->user_id]);
            Log::info("推送消息开始");
            if ($userInfo['subscribe'] == 1) {
                Log::info("进入推送1");
                $message = Push::where(["type" => 1])->find();
                if ($message) {
                    Log::info("进入推送2");
                    if (!empty($message['multiplejson'])) {
                        $json = json_decode($message['multiplejson'], true);
                        //参数名对应订阅消息详细内容参数 （以下为测试）
                        $data = [];
                        foreach ($json as $jv) {
                            switch ($jv['title']) {
                                case '1':
                                    $data['data'][$jv['keyword']]['value'] = $this->config['share_title'];
                                    break;
                                case '2':
                                    $data['data'][$jv['keyword']]['value'] = $order->order_no;
                                    break;
                                case '3':
                                    $data['data'][$jv['keyword']]['value'] = $order->order_amount_total;
                                    break;
                                case '4':
                                    $data['data'][$jv['keyword']]['value'] = date("Y-m-d H:i:s", time());
                                    break;

                            }
                        }
                        //Log::info("推送数据：" . json_encode($data['data']));
                        $data['order_id'] = $order['id'];
                        $data['openid'] = $userInfo['openid'];
                        $data['masterplate'] = $message->masterplate;
                        Queue::later(2, 'addons\fzdc\job\SendMessage', $data, 'dcOrderQueue');
                    }

                }

                //积分通知
                $message1 = Push::where(["type" => 2])->find();
                if ($message1) {
                    Log::info("进入积分推送2");
                    if (!empty($message1['multiplejson'])) {
                        $json = json_decode($message1['multiplejson'], true);
                        //参数名对应订阅消息详细内容参数 （以下为测试）
                        $data = [];
                        foreach ($json as $jv) {
                            switch ($jv['title']) {
                                case '10':
                                    $data['data'][$jv['keyword']]['value'] = \app\admin\model\User::where("id", $order['user_id'])->value("score");
                                    break;
                                case '11':
                                    $data['data'][$jv['keyword']]['value'] = '+'.$points;
                                    break;
                                case '12':
                                    $data['data'][$jv['keyword']]['value'] = $memo;
                                    break;
                                case '13':
                                    $data['data'][$jv['keyword']]['value'] = date("Y-m-d H:i:s", time());
                                    break;

                            }
                        }
                        //Log::info("积分推送数据：" . json_encode($data['data']));
                        $data['order_id'] = $order['id'];
                        $data['openid'] = $userInfo['openid'];
                        $data['masterplate'] = $message->masterplate;
                        Queue::later(2, 'addons\fzdc\job\SendMessage', $data, 'dcOrderQueue');
                    }

                }
            }
        } else {
            \app\admin\model\fzdc\order\Order::update(["status" => 1], ["order_no" => $data['out_trade_no']]);
        }
        Log::info("回调结束");
        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }

    /*
     * 打印小票
     */
    private function print($data)
    {

        $storeInfo = Store::where("id", $data['store_id'])->find();

        //获取打印机配置

        if ($storeInfo['print_sn'] == '') {
            Log::info("商家没有配置打印机!");
            return false;
        }

        $print = Prin::get(["id" => $storeInfo['print_sn'], "status" => "normal"]);
        if (!$print) {
            Log::info("未获取到打印机配置");
            return false;
        }

        try {
            \addons\fzdc\library\printer::printing($storeInfo, $print->id, $data['id']);
        } catch (\Throwable $e) {

            Log::info($e->getMessage());
            return false;
        }

        Log::info("打印成功");
        return true;
    }


}
